/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package it.polimi.deib.se2.meteocal.business.boundary;

import it.polimi.deib.se2.meteocal.business.entity.Group;
import it.polimi.deib.se2.meteocal.business.entity.User;
import java.security.Principal;
import java.util.List;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;


@Stateless
public class UserManager {
    
    @PersistenceContext
    EntityManager em;
    
    @Inject
    Principal principal;
    
    public void save(User user) {
        user.setGroupName(Group.USERS);
        em.persist(user);
    }
    
    public void edit(User user) {
        em.merge(user);
    }
    
    public User find(String email) {
        return em.find(User.class, email);
    }
    
    public void unregister() {
        em.remove(em.merge(getLoggedUser()));
    }
    
    public User getLoggedUser() {
        return em.find(User.class, principal.getName());
    }
    
    public List<User> getAllUsers(){
        Query q = em.createNativeQuery("SELECT * FROM meteocaldb.USERS",User.class);
        return q.getResultList();
    }
}